<template>
  <div>
    <!-- 定价规则表单 -->
    <el-form
      :model="priceRuleForm" 
      :rules="priceRuleForm.clear_mode==3?nosettle_priceRuleFormRules:priceRuleFormRules"
      ref="priceRuleFormRef"
      label-width="130px"
    >
      <el-form-item label="所属礼包" prop="gift"><!--required-->
        <el-input
          disabled
          placeholder="请输入所属礼包"
          v-model="priceRuleForm.gift_name"
          style="width:50%"
        > 
        </el-input>
      </el-form-item>
      <el-form-item label="所属采购实体"  prop="service_id"> 
          <el-select
            v-model="priceRuleForm.service_id"
            placeholder="请选择所属采购实体"
            filterable
            clearable
            style="width:50%"
            disabled
          >
             <el-option
                v-for="item in selectData.get_service"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              >
              </el-option> 
          </el-select> 
      </el-form-item>
      <el-form-item label="结算类型" prop="clear_mode">
       
          <el-select
            disabled
            v-model="priceRuleForm.clear_mode"
            placeholder="请选择结算类型"
            filterable
            clearable
            style="width:50%"
          >
             <el-option
                v-for="item in selectData.clear_mode"
                :key="item.id"
                :label="item.name"
                :value="typeof priceRuleForm.clear_mode=='string' ? item.id+'' :item.id" 
              ><!--:value="item.id"-->
              </el-option> 
          </el-select>
      </el-form-item>
      <el-form-item label="计价类型" v-show="priceRuleForm.clear_mode!=3" :required="priceRuleForm.clear_mode!=3?true:false" prop="valuation_type">
       
          <el-select
            v-model="priceRuleForm.valuation_type"
            placeholder="请选择"
            filterable
            clearable
            style="width:50%"
          >
            <el-option
                v-for="item in selectData.valuation_type"
                :key="item.id"
                :label="item.name" 
                :value="typeof priceRuleForm.valuation_type=='string' ? item.id+'' :item.id"  
              ><!--  :value="item.id" -->
            </el-option> 
          </el-select>
      </el-form-item> 
      <el-form-item label="统一价" prop="price" >
        <el-input
          :disabled="priceRuleForm.clear_mode==3?true:false"
          style="width:50%"
          placeholder="请输入统一价"
          v-model="priceRuleForm.price" 
        ><!--   oninput="value=value.replace(/[^\d.]/g,'')" -->
          <template slot="append">元</template>
        </el-input>
      </el-form-item>
      
      <el-form-item label="定价规则有效期" required style="width: 59%">
        <el-col :span="11">
          <el-form-item prop="start_time">
            <el-date-picker
              type="date"
              value-format="yyyy-MM-dd"
              placeholder="选择日期"
              v-model="priceRuleForm.start_time"
              style="width: 100%"
            ></el-date-picker>
          </el-form-item>
        </el-col>
        <el-col class="line" :span="1">-</el-col>
        <el-col :span="11">
          <el-form-item prop="end_time">
            <el-date-picker
              v-model="priceRuleForm.end_time"
              type="date"
              value-format="yyyy-MM-dd"
              placeholder="选择日期" 
              style="width: 100%"
            ></el-date-picker>
          </el-form-item>
        </el-col>
      </el-form-item>
      <el-form-item label="备注" prop="remark">
        <el-input
          v-model="priceRuleForm.remark"
          type="textarea" 
          show-word-limit
          maxlength="500"
          style="width:50%"
        ></el-input>
      </el-form-item>
      <el-form-item label="设置差异价" prop="is_diff">
        <el-switch v-model="priceRuleForm.is_diff"></el-switch>
      </el-form-item>
    </el-form>

    <div v-show="priceRuleForm.is_diff==true"><!---->
      <!-- 差异价规则表 --> 
      <el-table
        v-model="priceRuleForm.diff_rule"
        :data="diffTableData"  
        :rules="diffTableRules"
        ref="diffTableRef"
      
        border
        style="width: 100%"
        :row-class-name="tableRowClassName"
      >
        <el-table-column type="index" label="编号"> </el-table-column>
        <el-table-column prop="code" label="机构名称【ID】" width="200px">
           <template slot-scope="scope"> 
            <div
              v-if="(scope.row.id && scope.row.editRowVisible) || !scope.row.id"
            >
              <el-cascader
                :options="selectData.org_tree "
                :props="orgprops"
                clearable
                filterable
                :show-all-levels="false"
                v-model="scope.row.code"
                ref="myCascaderOrg"
                @change="changeOrg(scope.row)"
              ></el-cascader>
            </div>
            <div v-else>
              <span>{{ scope.row.code }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="area" label="地区名称">
          <template slot-scope="scope">
            <div
              v-if="(scope.row.id && scope.row.editRowVisible) || !scope.row.id"
            >
              <el-cascader
                :options="options"
                :props="areaprops"
                clearable
                filterable
                :show-all-levels="false"
                v-model="scope.row.area"
                ref="myCascader"
                @change="changeArea(scope.row)"
              ></el-cascader>
            </div>
            <div v-else>
              <span>{{ scope.row.area }}</span>
            </div>
          </template> 
        </el-table-column> 
        <el-table-column prop="price" label="合同价">
          <template slot-scope="scope">
            <div
              v-if="(scope.row.id && scope.row.editRowVisible) || !scope.row.id"
            >
              <el-input
                placeholder="请输入"
                v-model="scope.row.price"
                oninput="value=value.replace(/[^\d.]/g,'')"
              >
              </el-input>
            </div>
            <div v-else>
              <span>{{ scope.row.price }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-link
              type="warning"
              @click="editSingleDiffPriceRule(scope.row)"
              v-show="!scope.row.editRowVisible"
            > <!-- @click="scope.row.editRowVisible = true" -->
              编辑
            </el-link>
            <el-link
              type="success" 
              @click="saveSingleDiffPriceRule(scope.row)"
              v-show="scope.row.editRowVisible"
            >
              保存
            </el-link>
            &nbsp;
            <!--   
            <el-link
              type="warning"
              v-show="!scope.row.editRowVisible"
              @click="copyColumn(scope.row)"
            >
              复制
            </el-link>
            &nbsp;-->
            <el-link type="danger" @click="disable(scope.row)"><!--disable(scope.row.index)-->
              删除
            </el-link>
          </template> 
        </el-table-column>
      </el-table>

      <div class="addColumn">
        <el-button type="text" icon="el-icon-plus" @click="addColumnRule">
          增加差异规则
        </el-button>
      </div>
    </div>
 
  </div>
</template>

<script>
import regionData from '../../assets/js/regionChoose.js'
export default {
  props: { 
    PRData:{
      type: Object,
      default: function () {
        return {}
      }
    }
  }, 

  data() {
     
    return {
      selectData:{}, 
      priceRuleForm:{ 
      },
      priceRuleFormRules: {
      //  clear_mode: [{ required: true, message: '请选择结算类型', trigger: 'change' }],
        valuation_type: [{ required: true, message: '请选择计价类型', trigger: 'change' }],
        price: [{ required: true, message: '请输入统一价', trigger: 'change' }],
        start_time: [{ required: true, message: '请选择定价规则有效期', trigger: 'change' }],
        end_time: [{ required: true, message: '请选择定价规则有效期', trigger: 'change' }]
      },
      nosettle_priceRuleFormRules: { 
        start_time: [
          {
            required: true,
            message: '请选择日期',
            trigger: ['blur', 'change']
          }
        ],
        end_time: [
          {
            required: true,
            message: '请选择日期',
            trigger: ['blur', 'change']
          }
        ]
      },

      diffTableRules:{
        code: [{ required: true, message: '请选择机构名称', trigger: 'change' }],
        area: [{ required: true, message: '请选择地区名称', trigger: 'change' }],
        price: [{ required: true, message: '请输入合同价', trigger: 'change' }]
      },

      // 差异价规则表
      diffTableData: [],

      //org_options:[], //机构数
      options: [],
      orgprops: {
        checkStrictly: true,
        children: 'children',
        value: 'code',
        label: 'name',  
      },
      areaprops: {
        checkStrictly: true,
        children: 'childs',
        value: 'code',
        label: 'name', 
      },
      editDiffRow:'' //编辑的差异价
    }
  },
  watch: { 
    PRData:{
      handler(newValue, oldValue) {
        //  console.log('watch')
        //  console.log(oldValue) 
        //  console.log(newValue)
        this.priceRuleForm=JSON.parse(JSON.stringify(this.PRData)) 
        // console.log("获取到的PRData:")
        // console.log(this.priceRuleForm)
        this.getSelectData() 
      },
      deep: true
    }
  },
 
  created() {
     
    if(this.PRData){ 
     
      this.priceRuleForm=JSON.parse(JSON.stringify(this.PRData)) 

      // console.log("创建时带入的参数：") 
      // console.log(this.priceRuleForm)

      if(this.priceRuleForm.diff_rule.length>0){
        this.priceRuleForm.is_diff=true 
       
          for(var i=0;i<this.priceRuleForm.diff_rule.length;i++){
            var tempdiff={}
                tempdiff.editRowVisible=true  //false:20211207:为避免展示code码，展示为编辑状态 
                tempdiff.code=this.priceRuleForm.diff_rule[i].code
                tempdiff.area=this.priceRuleForm.diff_rule[i].area
                tempdiff.price=this.priceRuleForm.diff_rule[i].price
                tempdiff.id=this.priceRuleForm.diff_rule[i].id 
 
            this.diffTableData.push(tempdiff)
          }
  
        // console.log("初始化diffTableData数据：") 
        // console.log( this.diffTableData)
      }

      this.getSelectData()
    } 
    this.getOptions()   //获取城市： 
  },
 
  methods: { 
    async getSelectData() {   //获取筛选条件数据： 
      const { data: res } = await this.$http.post('/admin/data/find', {
        code: 'get_service,clear_mode,valuation_type,org_tree',partner_id:this.PRData.partner_id
      })
      // 返回结果
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      }
      this.selectData = res.data
    },
    getOptions() {
      var arr = regionData
      for (let i = 0; i < arr.length; i++) {
        for (let j = 0; j < arr[i].childs.length; j++) {
          delete arr[i].childs[j].childs
        }
      }
      this.options = arr 
      //this.org_options = this.selectData.org_tree  
    },
 
    tableRowClassName({ row, rowIndex }) {    //   把每一行的索引放进row 
      row.index = rowIndex
    },

    changeOrg(row){   //选择机构名称
      // console.log("选择机构名称:");
      // console.log(this.$refs.myCascaderOrg.getCheckedNodes())
      row.orgName = this.$refs.myCascaderOrg.getCheckedNodes().label
    },
    changeArea(row){ 
      // console.log(row)
      row.regionName = this.$refs.myCascader.getCheckedNodes().label
    },
    // copyColumn(row) {
    //   var newRow = Object.assign({}, row)
    //   newRow.id = ''
    //   newRow.editRowVisible = true
    //   console.log(newRow)
    //   this.diffTableData.splice(row.index + 1, 0, newRow) 
    // },
    disable(row) { 
    //删除差异价：
  
       this.$prompt('是否确认删除此差异价？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        inputPattern: /^(?!.{500}|^\s*$)/g,
        inputErrorMessage: '请输入删除原因',
        closeOnClickModal: false
      })
        .then(async ({ value }) => {
          // console.log(value)
          const { data: res } = await this.$http.post('/admin/gift/delDiffPriceRule', {
            id: row.id,
            reason: value 
          })
          if (res.meta.status !== 200) {
            return this.$message.error(res.meta.msg)
          }
          this.$message.success(res.meta.msg) 
          this.diffTableData.splice(row.index, 1)
        })
        .catch(() => {
        //  this.$message.info('已取消操作')
        })
  
    },
    addColumnRule() {
      this.diffTableData.push({ 
        code:'',
        area: '', 
        price: '',
        price_id: '', 
        editRowVisible: true
      })
    },
   
    async saveSingleDiffPriceRule(row){
     
      // console.log("保存单行差异价的数据：");
      // console.log(row)
  
      if(row.code && row.area && row.price){
        var dpitem = {} 
          if(typeof(row.code)=='string'){
            dpitem.code = row.code 
          }else{
            dpitem.code = row.code[row.code.length - 1]
          }
          if(typeof(row.area)=='string'){
            dpitem.area = row.area 
          }else{
            dpitem.area = row.area[row.area.length - 1]
          } 
          dpitem.price = row.price
         
          if(row.id == this.editDiffRow){
            
            dpitem.id = row.id  //编辑时的传参： 差异价id
            const { data: res } = await this.$http.post('/admin/gift/editDiffPriceRule',dpitem)

            if (res.meta.status !== 200) {
              return this.$message.error(res.meta.msg)
            }
            this.$message.success('编辑差异价成功') 
            row.editRowVisible = false
            this.editDiffRow='' //标记值归空
         

          }else{
            
            dpitem.price_id = this.PRData.id  //新增时的传参： 定价规则id
            const { data: res } = await this.$http.post('/admin/gift/addDiffPriceRule',dpitem)

            if (res.meta.status !== 200) {
              return this.$message.error(res.meta.msg)
            }
            this.$message.success('新增差异价成功') 
            // console.log(res.data)
            row.id=res.data.id
            row.editRowVisible = false
          }
       
      }else{
        this.$message.error('差异价参数缺失') 
      }
       
    },
    
    editSingleDiffPriceRule(row) {  //编辑无操作：只需切换表格展示  
      this.editDiffRow=row.id 
      this.diffTableData[row.index].editRowVisible = true 
      // console.log("切换编辑后的表格数据：")
      // console.log(this.diffTableData)
    },
    
    //校验数据：
    validateForm() {
      let flag = null
      this.$refs.priceRuleFormRef.validate(async (valid) => {
        if (valid) {
          flag = true
        } else {
          flag = false
        }
      })
      return flag
    },
    getFinalData() {
       if (this.priceRuleForm.is_diff && this.diffTableData.length === 0) {
         return this.$message.error('请配置差异价规则')
       }
      var diff = []
      for (let i = 0; i < this.diffTableData.length; i++) {
        const item = {}
        item.area = this.diffTableData[i].area[this.diffTableData[i].area.length - 1] 
        item.code = this.diffTableData[i].code[this.diffTableData[i].code.length - 1] 
        item.price = this.diffTableData[i].price
        // item.editRowVisible = false
        diff.push(item)
      }
      this.priceRuleForm.diff_rule = diff
      this.$emit('showPriceRuleRef', this.priceRuleForm)
    },
    
    // 清空数据
    resetAllData() {
      // 清空校验 
      this.$refs.priceRuleFormRef.resetFields() 
      this.diffTableData = []
      this.priceRuleForm={}
    }

  }
}
</script>
<style lang="less" scoped>
.addColumn {
  margin-top: -16px;
  text-align: center;
  border: 1px solid #eee;
  margin-bottom: 10px;
}
.line {
  text-align: center;
}
</style>
